package com.starsea.book.ui.newpage.weidget.flow

import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.blankj.utilcode.util.LogUtils
import com.starsea.book.R

/**
 * @author Lee
 * @createTime 2023-10-31 16 GMT+8
 * @desc :
 */
class JDFoldLayout @JvmOverloads constructor(
  context: Context,
  attrs: AttributeSet? = null,
  defStyleAttr: Int = 0
) : FlowListView(context, attrs, defStyleAttr) {
  private var upFoldView: View
  private var downFoldView: View
  private var canFold = false
  private var fold = false
  private var index = 0
  private var surplusWidth = 0

  init {
    upFoldView = LayoutInflater.from(context).inflate(R.layout.view_item_fold_up, null)
    downFoldView = LayoutInflater.from(context).inflate(R.layout.view_item_fold_down, null)
    upFoldView.setOnClickListener { _: View? ->
      mFold = false
      flowAdapter!!.notifyDataChanged()
    }
    downFoldView.setOnClickListener { _: View? ->
      mFold = true
      flowAdapter!!.notifyDataChanged()
    }

    setOnFoldChangedListener(object : OnFoldChangedListener {
      override fun onFoldChange(canFol: Boolean, fol: Boolean, inde: Int, surplusWidt: Int) {
        canFold = canFol
        fold = fol
        index = inde
        surplusWidth = surplusWidt
        refreshFoldView()
      }
    })

  }

  override fun updateView() {
    super.updateView()
    refreshFoldView()
  }

  var isAddDown = false
  var isAddUp = false

  private fun refreshFoldView() {
    removeFromParent(upFoldView)
    removeFromParent(downFoldView)
    if (canFold) {
      if (!isAddDown) {
        isAddDown = true
        addView(downFoldView)
      }
      if (fold) {
        isAddDown = false
        removeFromParent(upFoldView)
        val upIndex = index(index, surplusWidth)
        addView(upFoldView, upIndex)
      } else {
        LogUtils.e(">>>>>>  222fold = $fold")
        removeFromParent(downFoldView)
        addView(downFoldView)
      }
    }
  }

  private fun index(index: Int, surplusWidth: Int): Int {
    var upIndex = index
    var upWidth = getViewWidth(upFoldView)
    //当剩余空间大于等于展开View宽度直接加入index+1
    if (surplusWidth >= upWidth) {
      upIndex = index + 1
    } else { //找到对应的位置
      for (i in index downTo 0) {
        val view = getChildAt(index)
        val viewWidth = getViewWidth(view)
        upWidth -= viewWidth
        if (upWidth <= 0) {
          upIndex = i
          break
        }
      }
    }
    return upIndex
  }

  companion object {
    fun getViewWidth(view: View): Int {
      view.measure(0, 0)
      return view.measuredWidth
    }

    /**
     * 移除父布局中的子布局
     *
     * @param view
     */
    fun removeFromParent(view: View) {
      if (view.parent != null) {
        (view.parent as ViewGroup).removeView(view)
      }
    }
  }
}
